/**
 * @description 关于用户及登录的相关数据操作
 * @author zr
 */

import { login, logout, getUserInfo } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    userId: getToken(),
    name: '',
    avatar: '',
    userInfo: ''
  }
}

const state = getDefaultState()
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    // console.log(username, password)
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then((response) => {
          const { obj } = response
          // sessionStorage.setItem('rights', JSON.stringify(data.rightItems))
          //  const rights = JSON.parse(data.roleList[0].rights)
          // const path = rights.filter((v) => {
          //   return v.checkedRoles.length > 0
          // })[0].path
          commit('SET_USERINFO', obj)
          sessionStorage.setItem('userInfo', JSON.stringify(obj))
          setToken(obj)
          resolve(obj)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo({ userId: getToken() })
        .then((response) => {
          const { data } = response
          if (!data) {
            reject('验证失败，请重新登录！')
          }
          const { userName } = data
          commit('SET_NAME', userName)
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 用户退出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken()
          resetRouter()
          sessionStorage.clear()
          commit('RESET_STATE')
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 删除用户信息
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
